package cn.com.scan.activity;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.text.method.NumberKeyListener;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.HashMap;
import java.util.List;
import cn.com.scan.R;
import cn.com.scan.adapter.ImportItemAdapter;
import cn.com.scan.entity.ImportItem;
import cn.com.scan.jsonparser.ParseJson;
import cn.com.scan.netTools.RequestWebServive;
import cn.com.scan.netTools.ResultCode;
import cn.com.scan.tools.DialogUtils;

/**
 * Created by My on 2016/1/2.
 */
public class ImprotStorageActivity extends BaseActivity {
    private String ImportListMethod = "ReturnImportList";// 入库清单
    private String SubMitImpData="SubMitImpData";//修改到货信息
    private String SubmitImport="SubmitImport";//确认订单信息
    private int ImportListMethodTAG = 100;//入库标示
    private int SubMitImpDataTAG = 101;//修改标示
    private int SubmitImportTAG = 102;//确认标示
    private ListView listView;
    private TextView danHao, gongyingshang,user_name;
    private List<ImportItem> importItems;
    private String DOCUMENT_NO;//入库单号
    private String FIRM_NAME;//供应商名称
    private boolean isScanList = false;//是否扫描过清单文件
    private Button commit_button;
    private EditText input_num;
    ImportItemAdapter importItemAdapter;
    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            DialogUtils.closeProgressDialog();
            if (msg.what == ResultCode.SUCCESS) {
                handlerDisPose(msg);
            } else if (msg.what == ResultCode.IOFAILCODE) {
                Toast.makeText(ImprotStorageActivity.this, "服务器连接失败！", Toast.LENGTH_SHORT).show();
            } else if (msg.what == ResultCode.PARSERFAILCODE) {
                Toast.makeText(ImprotStorageActivity.this, "数据解析出错！", Toast.LENGTH_SHORT).show();
            } else {
                Toast.makeText(ImprotStorageActivity.this, "未知错误！", Toast.LENGTH_SHORT).show();
            }
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.import_storage_activity);
        danHao = (TextView) findViewById(R.id.danhao_text);
        input_num=(EditText)findViewById(R.id.input_num);
        gongyingshang = (TextView) findViewById(R.id.gongyingshang_text);
        user_name = (TextView) findViewById(R.id.user_name);
        listView = (ListView) findViewById(R.id.list_view);
        commit_button = (Button) findViewById(R.id.commit_button);
        commit_button.setOnClickListener(onclick);
        View headView = LayoutInflater.from(this).inflate(R.layout.import_storage_item, null, false);
        headView.setBackgroundResource(R.color.blue);
        importItemAdapter= new ImportItemAdapter(this);
        findViewById(R.id.search_button).setOnClickListener(onclick);
        listView.addHeaderView(headView);
        user_name.setText(user.getNAME());
        //listView.setOnItemLongClickListener(longClick);
        //数据模拟
//        HashMap<String, Object> map = new HashMap<String, Object>();
//        map.put("documentNo", "FH2016010400001");
//        requestNet(ImportListMethod, map, ImportListMethodTAG);

    }

    private View.OnClickListener onclick=new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            switch (v.getId()){
                case  R.id.search_button:
                    String documentNo=input_num.getText().toString();
                    HashMap<String, Object> map = new HashMap<String, Object>();
                    map.put("documentNo", documentNo);
                    requestNet(ImportListMethod, map, ImportListMethodTAG);
                    break;
                case R.id.commit_button:
                    AlertDialog.Builder alertBuilder = new AlertDialog.Builder(ImprotStorageActivity.this);
                    alertBuilder.setTitle("提示");
                    alertBuilder.setMessage("确定入库");
                    alertBuilder.setPositiveButton("确定",
                            new DialogInterface.OnClickListener() {
                                @Override
                                public void onClick(DialogInterface arg0, int arg1) {
                                    arg0.dismiss();
                                    HashMap<String, Object> map = new HashMap<String, Object>();
                                    map.put("documentNo", DOCUMENT_NO);
                                    map.put("userName", user.getUSER_NAME());
                                    requestNet(SubmitImport, map, SubmitImportTAG);
                                }
                            });
                    alertBuilder.setNegativeButton("取消",
                            new DialogInterface.OnClickListener() {

                                @Override
                                public void onClick(DialogInterface arg0, int arg1) {
                                    arg0.dismiss();
                                }
                            });
                    alertBuilder.show();
                    break;
            }

        }
    };
    @Override
    protected void broadcastExit() {
        this.finish();
    }

    @Override
    protected void capturePic(String codeStr) {
        if (isScanList) {
            HashMap<String, Object> map = new HashMap<String, Object>();
            map.put("documentNo", DOCUMENT_NO);
            map.put("barcode",codeStr);
            // map.put("quantity", 1);
            requestNet(SubMitImpData, map, SubMitImpDataTAG);
        } else {
            HashMap<String, Object> map = new HashMap<String, Object>();
            map.put("documentNo", codeStr);
            requestNet(ImportListMethod, map, ImportListMethodTAG);
        }
    }

    public void requestNet(String method, HashMap<String, Object> map, int TAG) {
        DialogUtils.showProgressDialog(ImprotStorageActivity.this);
        RequestWebServive requestWebServive = new RequestWebServive(method, handler, map, TAG);
        requestWebServive.start();
    }

    private void handlerDisPose(Message msg) {
        String str = (String) msg.obj;
        if (!TextUtils.isEmpty(str)) {
            try {
                JSONObject  jsonObject=new JSONObject(str);
               int code=jsonObject.getInt("CODE");
                if(code==0 & !TextUtils.isEmpty(str)){
                    String RESULT = jsonObject.getString("RESULT");
                    if (msg.arg1 == ImportListMethodTAG) {
                            isScanList=true;
                            listView.setVisibility(View.VISIBLE);
                            importItems = ParseJson.parseImportItem(RESULT);
                            DOCUMENT_NO=importItems.get(0).getDOCUMENT_NO();
                            FIRM_NAME=importItems.get(0).getFIRM_NAME();
                            gongyingshang.setText(FIRM_NAME);
                            danHao.setText(DOCUMENT_NO);
                            importItemAdapter.setList(importItems);
                            listView.setAdapter(importItemAdapter);
                    } else if (msg.arg1 == SubMitImpDataTAG) {

                            listView.setVisibility(View.VISIBLE);
                            importItems = ParseJson.parseImportItem(RESULT);
                            DOCUMENT_NO=importItems.get(0).getDOCUMENT_NO();
                            FIRM_NAME=importItems.get(0).getFIRM_NAME();
                            gongyingshang.setText(FIRM_NAME);
                            danHao.setText(DOCUMENT_NO);
                            importItemAdapter.setList(importItems);
                            listView.setAdapter(importItemAdapter);

                    }else if(msg.arg1 ==SubmitImportTAG){
                        Toast.makeText(ImprotStorageActivity.this, "订单提交成功！", Toast.LENGTH_SHORT).show();
                        importItemAdapter.setList(null);
                        DOCUMENT_NO="";
                        FIRM_NAME="";
                        gongyingshang.setText("");
                        danHao.setText("");

                    }
                }else{
                    Toast.makeText(ImprotStorageActivity.this, jsonObject.getString("MSG"), Toast.LENGTH_SHORT).show();
                }
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }
    }
//    public AdapterView.OnItemLongClickListener longClick = new AdapterView.OnItemLongClickListener() {
//        @Override
//        public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
//            final ImportItem im = importItems.get(position - 1);
//            final EditText et = new EditText(ImprotStorageActivity.this);
//            et.setKeyListener(watcher);
//            AlertDialog.Builder alertBuilder = new AlertDialog.Builder(ImprotStorageActivity.this);
//            alertBuilder.setTitle("请输入\"" + im.getEXP_NAME() + "\"到货数量");
//            alertBuilder.setView(et);
//            alertBuilder.setPositiveButton("确定",
//                    new DialogInterface.OnClickListener() {
//                        @Override
//                        public void onClick(DialogInterface arg0, int arg1) {
//                            arg0.dismiss();
//                            HashMap<String, Object> map = new HashMap<String, Object>();
//                            map.put("documentNo", DOCUMENT_NO);
//                            map.put("barcode",im.getBARCODE());
//                            map.put("quantity", et.getText().toString());
//                            requestNet(SubMitImpData, map, SubMitImpDataTAG);
//                        }
//                    });
//            alertBuilder.setNegativeButton("取消",
//                    new DialogInterface.OnClickListener() {
//
//                        @Override
//                        public void onClick(DialogInterface arg0, int arg1) {
//                            arg0.dismiss();
//                        }
//                    });
//            alertBuilder.show();
//            return false;
//        }
//    };
//    private NumberKeyListener watcher = new NumberKeyListener() {
//        @Override
//        public int getInputType() {
//            return android.text.InputType.TYPE_CLASS_NUMBER;
//        }
//
//        @Override
//        protected char[] getAcceptedChars() {
//            return new char[] { '1', '2', '3', '4', '5', '6', '7', '8',
//                    '9', '0','.'};
//        }
//    };
}
